//! CDB数据库集成测试
//! 
//! 测试数据库的完整功能流程

use cdb::{Database, Result};
use cdb::storage::{TableSchema, ColumnDefinition, DataType};
use cdb::sql::Value;

#[tokio::test]
async fn test_database_lifecycle() -> Result<()> {
    // 创建数据库实例
    let database = Database::new().await?;
    
    // 创建连接
    let mut connection = database.connect().await?;
    
    // 测试基础连接
    assert!(!connection.in_transaction());
    
    // 关闭数据库
    database.close().await?;
    
    Ok(())
}

#[tokio::test]
async fn test_table_operations() -> Result<()> {
    let database = Database::new().await?;
    let mut connection = database.connect().await?;
    
    // 这里可以添加表操作测试
    // 由于当前SQL解析器还有问题，先测试基础功能
    
    database.close().await?;
    Ok(())
}

#[tokio::test]
async fn test_transaction_operations() -> Result<()> {
    let database = Database::new().await?;
    let mut connection = database.connect().await?;

    // 测试事务开始
    let _transaction = connection.begin_transaction().await?;
    assert!(connection.in_transaction());

    // 测试事务提交
    connection.commit().await?;
    assert!(!connection.in_transaction());

    database.close().await?;
    Ok(())
}

#[tokio::test]
async fn test_multiple_connections() -> Result<()> {
    let database = Database::new().await?;
    
    // 创建多个连接
    let _conn1 = database.connect().await?;
    let _conn2 = database.connect().await?;
    
    assert_eq!(database.connection_count(), 2);
    
    database.close().await?;
    Ok(())
}

#[test]
fn test_value_types() {
    // 测试数据值类型
    let values = vec![
        Value::Null,
        Value::Boolean(true),
        Value::Integer(42),
        Value::Real(3.14),
        Value::Text("test".to_string()),
        Value::Timestamp(chrono::Utc::now()),
    ];
    
    for value in values {
        // 测试序列化和反序列化
        let serialized = serde_json::to_string(&value).unwrap();
        let deserialized: Value = serde_json::from_str(&serialized).unwrap();
        assert_eq!(value, deserialized);
    }
}

#[test]
fn test_table_schema() {
    let schema = TableSchema::new(vec![
        ColumnDefinition {
            name: "id".to_string(),
            data_type: DataType::Integer,
            nullable: false,
            primary_key: true,
        },
        ColumnDefinition {
            name: "name".to_string(),
            data_type: DataType::String(Some(50)),
            nullable: false,
            primary_key: false,
        },
        ColumnDefinition {
            name: "age".to_string(),
            data_type: DataType::Integer,
            nullable: true,
            primary_key: false,
        },
    ]);
    
    let column_names = schema.column_names();
    assert_eq!(column_names, vec!["id", "name", "age"]);
    
    // 测试序列化
    let serialized = serde_json::to_string(&schema).unwrap();
    let deserialized: TableSchema = serde_json::from_str(&serialized).unwrap();
    assert_eq!(schema.columns.len(), deserialized.columns.len());
}

#[tokio::test]
async fn test_memory_management() -> Result<()> {
    use cdb::config::DatabaseConfig;
    use cdb::storage::memory::MemoryManager;
    
    let config = DatabaseConfig::default();
    let memory_manager = MemoryManager::new(&config)?;
    
    // 测试页面分配
    let page_id = memory_manager.allocate_page()?;
    assert!(memory_manager.memory_usage() > 0);
    
    // 测试页面写入和读取
    let test_data = vec![1, 2, 3, 4, 5];
    memory_manager.write_page(page_id, test_data.clone())?;
    let read_data = memory_manager.get_page(page_id)?;
    assert_eq!(read_data[0..5], test_data[..]);
    
    // 测试页面释放
    memory_manager.deallocate_page(page_id)?;
    
    Ok(())
}

#[test]
fn test_index_operations() -> Result<()> {
    use cdb::storage::index::IndexManager;
    
    let mut index_manager = IndexManager::new();
    
    // 创建B+树索引
    index_manager.create_btree_index("test_btree".to_string(), "id".to_string())?;
    
    // 创建哈希索引
    index_manager.create_hash_index("test_hash".to_string(), "name".to_string())?;
    
    // 验证索引存在
    assert!(index_manager.get_index("test_btree").is_some());
    assert!(index_manager.get_index("test_hash").is_some());
    
    // 获取索引统计
    let stats = index_manager.get_stats();
    assert!(stats.total_indexes >= 2);
    
    Ok(())
}

#[test]
fn test_metrics_collection() {
    use cdb::utils::metrics::MetricsCollector;
    use std::time::Duration;
    
    let collector = MetricsCollector::new();
    
    // 测试查询指标
    let query_metrics = collector.query_metrics();
    let timer = query_metrics.query_started();
    std::thread::sleep(Duration::from_millis(10));
    timer.finish(true, Duration::from_millis(100));
    
    let snapshot = query_metrics.get_snapshot();
    assert_eq!(snapshot.total_queries, 1);
    assert_eq!(snapshot.successful_queries, 1);
    
    // 测试存储指标
    let storage_metrics = collector.storage_metrics();
    storage_metrics.record_read(1024);
    storage_metrics.record_cache_hit();
    
    let storage_snapshot = storage_metrics.get_snapshot();
    assert_eq!(storage_snapshot.reads, 1);
    assert_eq!(storage_snapshot.bytes_read, 1024);
    assert_eq!(storage_snapshot.cache_hits, 1);
}

#[test]
fn test_configuration() -> Result<()> {
    use cdb::utils::config::{Config, ConfigBuilder};
    use tempfile::NamedTempFile;
    
    // 测试配置构建器
    let config = ConfigBuilder::new()
        .memory_limit(1024 * 1024 * 1024) // 1GB
        .max_connections(100)
        .postgres_port(5433)
        .build()?;
    
    assert_eq!(config.database.memory_limit, 1024 * 1024 * 1024);
    assert_eq!(config.database.max_connections, 100);
    assert_eq!(config.network.postgres_port, 5433);
    
    // 测试配置文件保存和加载
    let temp_file = NamedTempFile::new().unwrap();
    config.save_to_file(temp_file.path())?;
    
    let loaded_config = Config::from_file(temp_file.path())?;
    assert_eq!(config.database.memory_limit, loaded_config.database.memory_limit);
    
    Ok(())
}
